﻿using GPSTrackingWebsiteManager.ClassManager;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class StockFile : SessionManagerPage
    {
        private void GetAllStockFiles()
        {
            SessionManager objSessionManager = new SessionManager();
            objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            GPSTrackingDBV2.Data.StockFilesQuery stockFilesQuery = new GPSTrackingDBV2.Data.StockFilesQuery();
            stockFilesQuery.AppendEquals(GPSTrackingDBV2.Entities.StockFilesColumn.CompanyId, objSessionManager.CompanyIDSelectedComboBox.ToString());
            StockFileGrid.DataSource = GPSTrackingDBV2.Data.DataRepository.StockFilesProvider.Find(stockFilesQuery);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                sdsFileType.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;                

                if (!Page.IsPostBack)
                {
                    GridSortExpression expression = new GridSortExpression();
                    expression.FieldName = GPSTrackingDBV2.Entities.StockFilesColumn.Name.ToString();
                    expression.SetSortOrder("Ascending");
                    this.StockFileGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
                }

            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede iniciar los datos de la sección");
            }
        }
        
        protected void StockFileGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                //Transaction
                tm.BeginTransaction();

                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                GPSTrackingDBV2.Entities.StockFiles StockFileEntity = ClassManager.InvokeEntityManager.Invoke_StockFile_Entity(e);

                StockFileEntity.StockFileId = GPSTrackingDBV2Custom.Data.DataRepository.StockFilesProvider.GetNextID();
                StockFileEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;

                //string Path = "~/PointOfSale/StockFiles/" + objSessionManager.GUID + "/";

                GridEditFormInsertItem InsertItem = e.Item as GridEditFormInsertItem;
                RadAsyncUpload RadUpload = InsertItem["StockFileTypeOfFileId"].FindControl("RadUpload1") as RadAsyncUpload;
                StockFileEntity.Filename = RadUpload.UploadedFiles[0].FileName;
                //StockFileEntity.Filename = RadUpload.UploadedFiles[0].FileName.Replace(RadUpload.UploadedFiles[0].GetExtension(), "_" + StockFileEntity.StockFileId + RadUpload.UploadedFiles[0].GetExtension());

                if (RadUpload.UploadedFiles.Count > 0)
                {
                    String path = GetPathToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    RadUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockFile(StockFileEntity.Filename)));
                }

                //Log
                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);

                GPSTrackingDBV2.Entities.StockFilesLog StockFilesLogEntity = new GPSTrackingDBV2.Entities.StockFilesLog();
                StockFilesLogEntity.CompanyId = objSessionManager.CompanyIDSelectedComboBox;
                StockFilesLogEntity.StockFileId = StockFileEntity.StockFileId;
                StockFilesLogEntity.TransactionDate = dateTransaction;
                StockFilesLogEntity.Tick = tick;
                StockFilesLogEntity.SyncTransaction = SessionManager.SysnTransactionType_Insert;

                StockFilesLogEntity.Name = StockFileEntity.Name;
                StockFilesLogEntity.Filename = StockFileEntity.Filename;
                StockFilesLogEntity.StockFileTypeOfFileId = StockFileEntity.StockFileTypeOfFileId;

                Dictionary<string, string> AttribTransacion = objSessionManager.GetAttribTransaction();

                StockFilesLogEntity.TypeUserTransaction = AttribTransacion[SessionManager.AttribTransaction.TypeUserTransaction.ToString()];
                StockFilesLogEntity.UsernameTransaction = AttribTransacion[SessionManager.AttribTransaction.UsernameTransaction.ToString()]; ;
                StockFilesLogEntity.CompanyIdTransaction = objSessionManager.CompanyIDSelectedComboBox;

                

                    StockFileEntity.LastTick = tick;
                    GPSTrackingDBV2.Data.DataRepository.StockFilesProvider.Insert(tm, StockFileEntity);

                    GPSTrackingDBV2.Data.DataRepository.StockFilesLogProvider.Insert(tm, StockFilesLogEntity);

                tm.Commit();

                
            }
            catch (Exception ex)
            {
                tm.Rollback();

                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede insertar la información.");
            }

        }

        protected void StockFileGrid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try               
            {
                //Transaction
                tm.BeginTransaction();
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                GPSTrackingDBV2.Entities.StockFiles StockFileEntity = ClassManager.InvokeEntityManager.Invoke_StockFile_Entity(e);

                string filenameUrlToDelete = String.Empty;

                GridEditFormItem EditItem = e.Item as GridEditFormItem;
                RadAsyncUpload RadUpload = EditItem["StockFileTypeOfFileId"].FindControl("RadUpload1") as RadAsyncUpload;
                if (RadUpload.UploadedFiles.Count > 0)
                {

                    //string Path = "~/PointOfSale/StockFiles/" + objSessionManager.GUID + "/";

                    //StockFileEntity.Filename = RadUpload.UploadedFiles[0].FileName.Replace(RadUpload.UploadedFiles[0].GetExtension(), "_" + StockFileEntity.StockFileId + RadUpload.UploadedFiles[0].GetExtension()); //RadUpload.UploadedFiles[0].FileName;
                    StockFileEntity.Filename = RadUpload.UploadedFiles[0].FileName;
                    if (RadUpload.ToolTip != StockFileEntity.Filename) filenameUrlToDelete = RadUpload.ToolTip;
                    RadUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockFile(StockFileEntity.Filename)));                   


                }
                else
                {
                    StockFileEntity.Filename = RadUpload.ToolTip;
                }
                StockFileEntity.OriginalCompanyId = StockFileEntity.CompanyId;
                StockFileEntity.OriginalStockFileId = StockFileEntity.StockFileId;


                //Log
                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);

                GPSTrackingDBV2.Entities.StockFilesLog StockFilesLogEntity = new GPSTrackingDBV2.Entities.StockFilesLog();
                StockFilesLogEntity.CompanyId = StockFileEntity.CompanyId;
                StockFilesLogEntity.StockFileId = StockFileEntity.StockFileId;
                StockFilesLogEntity.TransactionDate = dateTransaction;
                StockFilesLogEntity.Tick = tick;
                StockFilesLogEntity.SyncTransaction = SessionManager.SysnTransactionType_Update;

                StockFilesLogEntity.Name = StockFileEntity.Name;
                StockFilesLogEntity.Filename = StockFileEntity.Filename;
                StockFilesLogEntity.StockFileTypeOfFileId = StockFileEntity.StockFileTypeOfFileId;


                
                Dictionary<string, string> AttribTransacion = objSessionManager.GetAttribTransaction();

                StockFilesLogEntity.TypeUserTransaction = AttribTransacion[SessionManager.AttribTransaction.TypeUserTransaction.ToString()];
                StockFilesLogEntity.UsernameTransaction = AttribTransacion[SessionManager.AttribTransaction.UsernameTransaction.ToString()];
                StockFilesLogEntity.CompanyIdTransaction = objSessionManager.CompanyIDSelectedComboBox;

                

                    StockFileEntity.LastTick = tick;
                    GPSTrackingDBV2.Data.DataRepository.StockFilesProvider.Update(tm, StockFileEntity);

                    if (!String.IsNullOrEmpty(filenameUrlToDelete))
                        System.IO.File.Delete(Server.MapPath(GetPathStockFile(filenameUrlToDelete)));

                    GPSTrackingDBV2.Data.DataRepository.StockFilesLogProvider.Insert(tm, StockFilesLogEntity);

                tm.Commit();


                
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede actualizar la información.");
            }
        }

        public string GetPathFile()
        {
            return "../../PointOfSale/StockFiles/" + getSessionManager().GUID + "/";
        }

        public string GetPathToCreate()
        {
            return "../../PointOfSale/StockFiles/" + getSessionManager().GUID;
        }


        public string GetPathStockFile(string fileUrl)
        {
            return "../../PointOfSale/StockFiles/" + getSessionManager().GUID + "/" + fileUrl;
        }


        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void StockFileGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                //Transaction
                tm.BeginTransaction();

                GPSTrackingDBV2.Entities.StockFiles StockFileEntity = ClassManager.InvokeEntityManager.Invoke_StockFile_Entity(e);                

                //Log
                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);

                GPSTrackingDBV2.Entities.StockFilesLog StockFilesLogEntity = new GPSTrackingDBV2.Entities.StockFilesLog();
                StockFilesLogEntity.CompanyId = StockFileEntity.CompanyId;
                StockFilesLogEntity.StockFileId = StockFileEntity.StockFileId;
                StockFilesLogEntity.TransactionDate = dateTransaction;
                StockFilesLogEntity.Tick = tick;
                StockFilesLogEntity.SyncTransaction = SessionManager.SysnTransactionType_Delete;

                StockFilesLogEntity.Name = StockFileEntity.Name;
                StockFilesLogEntity.Filename = GPSTrackingDBV2.Data.DataRepository.StockFilesProvider.GetByCompanyIdStockFileId(getSessionManager().CompanyIDSelectedComboBox, StockFileEntity.StockFileId).Filename; //StockFileEntity.Filename;
                StockFilesLogEntity.StockFileTypeOfFileId = StockFileEntity.StockFileTypeOfFileId;

                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
                Dictionary<string, string> AttribTransacion = objSessionManager.GetAttribTransaction();

                StockFilesLogEntity.TypeUserTransaction = AttribTransacion[SessionManager.AttribTransaction.TypeUserTransaction.ToString()];
                StockFilesLogEntity.UsernameTransaction = AttribTransacion[SessionManager.AttribTransaction.UsernameTransaction.ToString()];
                StockFilesLogEntity.CompanyIdTransaction = objSessionManager.CompanyIDSelectedComboBox;

                

                    StockFileEntity.LastTick = tick;
                    GPSTrackingDBV2.Data.DataRepository.StockFilesProvider.Delete(tm, StockFileEntity);

                    System.IO.File.Delete(Server.MapPath(GetPathStockFile(StockFilesLogEntity.Filename)));

                    GPSTrackingDBV2.Data.DataRepository.StockFilesLogProvider.Insert(tm, StockFilesLogEntity);

                tm.Commit();                
               
            }
            catch (Exception ex)
            {
                tm.Rollback();

                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede eliminar el registro porque el archivo se encuentra asociados a otros registros.");
            }
        }

        protected void StockFileGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetAllStockFiles();
                StockFileGrid.Height = Unit.Parse(HiddenFieldHeight.Value.ToString());
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("Se ha presentado un error en la carga de los datos");
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            StockFileGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in StockFileGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }

                if (column is GridDropDownColumn)
                {
                    GridDropDownColumn dropDownColumn = column as GridDropDownColumn;
                    dropDownColumn.CurrentFilterValue = string.Empty;
                }
            }


            StockFileGrid.MasterTableView.Rebind();
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Archivos ...');", true);
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public System.Drawing.Image ResizeImageFixedWidth(System.Drawing.Image imgToResize, int width)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = ((float)width / (float)sourceWidth);

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (System.Drawing.Image)b;
        }
    }
}